package com.woniu.auth;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.woniu.dao.UsersMapper;
import com.woniu.util.JwtTokenUtil;
import com.woniu.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Component
public class MyLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UsersMapper usersMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        String username = request.getParameter("username");
        String token = "";
        try {
            token = JwtTokenUtil.createSign(username);
            System.out.println(token);
            //用户的权限信息存redis
            //List<GrantedAuthority> authroies = new ArrayList<>();
            List<String> lists = usersMapper.getPermsCodeByUserName(username);
           /* for(String str : lists){
                GrantedAuthority ge = new SimpleGrantedAuthority(str);
                authroies.add(ge);
            }*/
            String tempPerm = new ObjectMapper().writeValueAsString(lists);
            redisTemplate.opsForValue().set("RoleCode:" + username,tempPerm,60, TimeUnit.DAYS);
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        ResponseResult<String> success = new ResponseResult<String>(token,"登陆成功",200);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(success));

    }
}
